"""
Case Type   : 多节点写入
Case Name   : 扩展查询之查询异常测试
Create At   : 2023/1/29
Owner       : @li-xin12345
Description :
    1.修改enable_remote_execute参数值为on
    2.扩展查询之查询异常测试
    3.查看日志打印
    4.环境清理，恢复参数
Expect      :
    1.修改成功
    2.合理报错
    3.日志记录libpqsw:P报文信息，转发给主机
    4.环境清理成功，恢复参数成功
History     :
    Modified by @kyeleze 2023/7/5:研发代码变更，日志打印信息更改，优化断言以适配新代码
"""
import os
import re
import time
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant

PrimarySh = CommonSH('PrimaryDbUser')


@unittest.skipIf(3 != PrimarySh.get_node_num(), '非1主2备环境不执行')
class MultiNodeWrite(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f"-----{os.path.basename(__file__)} start-----")
        self.primary_root = Node('PrimaryRoot')
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.standby_root = Node('Standby2Root')
        self.standby_node = Node('Standby2DbUser')
        self.standby_sh = CommonSH('Standby2DbUser')
        self.constant = Constant()
        self.common = Common('Standby2DbUser')
        self.common_root = Common('Standby2Root')
        self.common_pri = Common('PrimaryRoot')
        self.table_name = 't_multi_node_write_0040'
        self.java_file_name = "Opengauss_Function_MultiNodeWrite_Case0040"
        self.java_file = '.'.join([self.java_file_name, 'java'])
        self.java_file_path = os.path.join(macro.SCRIPTS_PATH, self.java_file)
        self.target_path = os.path.join(macro.DB_BACKUP_PATH,
                                        'JDBC_multi_node_write_0040')
        self.properties = os.path.join(
            self.target_path, 'JDBC_MultiNodeWrite_Case0040.properties')
        self.new_jdbc_path = os.path.join(self.target_path, 'postgresql.jar')
        self.new_log_path = os.path.join(macro.PG_LOG_PATH,
                                         'pg_log_multi_node_write_case0040')
        self.enable_remote_execute = 'enable_remote_execute'
        self.log_statement = 'log_statement'
        self.log_directory = 'log_directory'
        self.remote_execute_default = self.common.show_param(
            self.enable_remote_execute)
        self.log_statement_default = self.common.show_param(self.log_statement)
        self.log_dir_default = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.new_log_path} {self.target_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_root, shell_cmd)
        self.assertEquals('', shell_msg, '删除目录失败')

    def test_multi_node_write(self):
        step1 = "-----step1:修改enable_remote_execute参数值为on;expect:修改成功-----"
        self.logger.info(step1)
        result = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}=on')
        self.assertTrue(result, '执行失败' + step1)
        restart_res = self.standby_sh.restart_db_cluster()
        self.assertTrue(restart_res, '执行失败' + step1)
        show_remote_execute = self.common.show_param(self.enable_remote_execute)
        self.assertEquals(show_remote_execute, 'on', '执行失败' + step1)
        result = self.standby_sh.execute_gsguc('reload',
                                               self.constant.GSGUC_SUCCESS_MSG,
                                               f'{self.log_statement}=all')
        self.assertTrue(result, '执行失败' + step1)
        result = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.new_log_path}\'', single=True)
        self.assertTrue(result, '执行失败' + step1)
        show_log_statement = self.common.show_param(self.log_statement)
        self.assertEquals(show_log_statement, 'all', '执行失败' + step1)
        show_log_directory = self.common.show_param(self.log_directory)
        self.assertEquals(show_log_directory, self.new_log_path, '执行失败' + step1)

        step2 = "-----step2:扩展查询之查询异常测试;expect:合理报错-----"
        self.logger.info(step2)
        self.logger.info('-----创建配置文件;expect:创建成功-----')
        self.common_pri.scp_file(self.standby_root, self.java_file,
                                 self.target_path)
        touch_res = self.common_root.get_sh_result(self.standby_root,
                                                   f"touch {self.properties}")
        self.assertEquals('', touch_res, '创建配置文件失败')
        config = f'echo "password=' \
            f'{self.standby_node.db_password}"> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "port={self.standby_node.db_port}">> ' \
            f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "hostname={self.standby_node.db_host}">> ' \
            f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "user={self.standby_node.db_user}">> ' \
            f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "dbname={self.standby_node.db_name}">> ' \
            f'{self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        config = f'echo "tbname={self.table_name}">> {self.properties}'
        self.common_root.get_sh_result(self.standby_root, config)
        shell_cmd = f'cat {self.properties}'
        self.logger.info(shell_cmd)
        shell_msg = self.common_root.get_sh_result(self.standby_root, shell_cmd)
        self.assertTrue("password=" in shell_msg and "port=" in shell_msg
                        and "hostname=" in shell_msg and "user=" in shell_msg
                        and "dbname=" in shell_msg and "tbname=" in shell_msg,
                        '创建配置文件失败')
        shell_cmd = f"cp {macro.JDBC_PATH} {self.new_jdbc_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common_root.get_sh_result(self.standby_root, shell_cmd)
        self.logger.info(shell_msg)
        shell_msg = self.common_root.get_sh_result(self.standby_root,
                                                   f"ls {self.new_jdbc_path}")
        self.assertNotIn(self.constant.NO_FILE_MSG, shell_msg, '拷贝失败')

        self.logger.info('-----编译java文件;expect:编译成功-----')
        compile_cmd = f"cd {self.target_path};" \
            f"javac -encoding utf-8 -cp {self.new_jdbc_path} {self.java_file}"
        self.logger.info(compile_cmd)
        compile_msg = self.common_root.get_sh_result(self.standby_root,
                                                     compile_cmd)
        self.assertNotIn('ERROR', compile_msg, '编译失败')

        self.logger.info('-----运行java预编译代码;expect:运行成功-----')
        java_cmd = f"cd {self.target_path};" \
            f"java -cp {self.new_jdbc_path}:{self.target_path} " \
            f"{self.java_file_name} -F {self.properties}"
        self.logger.info(java_cmd)
        java_msg = self.common_root.get_sh_result(self.standby_root, java_cmd)
        self.assertIn(f'ERROR: relation "{self.table_name}" does not exist',
                      java_msg, '运行失败')
        time.sleep(3)

        step3 = "-----step3:查看日志打印;expect:日志记录libpqsw:P报文信息，转发给主机-----"
        self.logger.info(step3)
        shell_cmd = f"ls -t {self.new_log_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        logfile = os.path.join(self.new_log_path, shell_msg.split()[-1])
        self.logger.info(logfile)
        shell_cmd = f"cat {logfile} "
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_node, shell_cmd)
        self.logger.info(shell_msg)
        self.assertIn(f'we find pbe new select cmdtag',
                      shell_msg, '执行失败:' + step3)
        expect = "LOG:  libpqsw.*P.*"
        search_res = re.search(expect, shell_msg, re.S)
        self.assertIsNotNone(search_res, '执行失败' + step3)

    def tearDown(self):
        step4 = "-----step4:环境清理，恢复参数;expect:环境清理成功，恢复参数成功-----"
        self.logger.info(step4)
        result1 = self.standby_sh.execute_gsguc(
            'set', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.enable_remote_execute}={self.remote_execute_default}')
        restart_res = self.standby_sh.restart_db_cluster()
        show_remote_execute = self.common.show_param(self.enable_remote_execute)
        result2 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_statement}={self.log_statement_default}')
        result3 = self.standby_sh.execute_gsguc(
            'reload', self.constant.GSGUC_SUCCESS_MSG,
            f'{self.log_directory}=\'{self.log_dir_default}\'', single=True)
        show_log_statement = self.common.show_param(self.log_statement)
        show_log_directory = self.common.show_param(self.log_directory)
        shell_cmd = f"rm -rf {self.target_path}"
        self.logger.info(shell_cmd)
        shell_msg = self.common.get_sh_result(self.standby_root, shell_cmd)
        self.logger.info("-----断言teardown-----")
        self.assertTrue(result1, '执行失败' + step4)
        self.assertTrue(restart_res, '执行失败' + step4)
        self.assertEquals(show_remote_execute, self.remote_execute_default,
                          '执行失败' + step4)
        self.assertTrue(result2, '执行失败' + step4)
        self.assertTrue(result3, '执行失败' + step4)
        self.assertEquals(show_log_statement, self.log_statement_default,
                          '执行失败' + step4)
        self.assertEquals(show_log_directory, self.log_dir_default,
                          '执行失败' + step4)
        self.assertEquals('', shell_msg, '删除目录失败')
        self.logger.info(f"-----{os.path.basename(__file__)} end-----")
